#include "RenderObjectManager.h"
RenderObjectManager::RenderObjectManager()
	:Component(COMP_RENDER_OBJ_MANGER)
{
	m_dumpFile.open(RENDER_DUMP_FILENAME,fstream::trunc|fstream::out);
	if(!m_dumpFile.is_open())
	{
		EXCEPTION("Can not open dump file")
	}
}

RenderObjectManager::~RenderObjectManager()
{
	if(m_dumpFile)
	{
		m_dumpFile.close();
	}
}

void RenderObjectManager::AddedToObject()
{
	RequestMessage(MSG_INITIAL_GRAPHICS,&RenderObjectManager::Initialize);
	RequestMessage(MSG_DUMP_ALL_MESSAGE,&RenderObjectManager::Dump);
	RequestMessage(MSG_ADD_RENDER_OBJECT,&RenderObjectManager::AddRenderObject);
	RequestMessage(MSG_REMOVE_RENDER_OBJECT,&RenderObjectManager::RemoveRenderObject);
	RequestMessage(MSG_REMOVE_ALL_RENDER_QUEUE,&RenderObjectManager::RemoveAllQueue);
}

void RenderObjectManager::Initialize(const Message& msg)
{
	boost::shared_ptr<RenderQueue> rq=boost::make_shared<RenderQueue>();
	AddLocalComponent(rq);

	string path;
	SendMessage(MSG_GET_PATH,AuxGroupArgus(string("default.fx"),&path));

	rq->Initial(path);
	m_renderQueueMap[QueueMain]=rq;
}

void RenderObjectManager::Render()
{
	for(RenderQueueMap::iterator iter=m_renderQueueMap.begin();iter!=m_renderQueueMap.end();iter++)
	{
		RenderSignleQueue(iter->second);
	}
}

//Add all render object to QueueMain queue now.
//Need be split to different queue according to different technology in the future.
void RenderObjectManager::AddRenderObject(const Message& msg)
{
	try
	{
		boost::shared_ptr<RenderObject> obj;
		AuxUnGroupArgus(msg.p,obj);
		m_renderQueueMap[QueueMain]->AddRenderObject(obj);
	}
	catch(boost::bad_any_cast& e)
	{
		PRINT_BOOST_ERROR(e)
	}
	catch(std::exception& e)
	{
		PRINT_ERROR(e)
	}

}

void RenderObjectManager::RenderSignleQueue(RenderQueue::sPtr rp)
{
	rp->Render();
}

void RenderObjectManager::Dump(const Message& msg)
{
	for(RenderQueueMap::iterator iter=m_renderQueueMap.begin();iter!=m_renderQueueMap.end();iter++)
	{
		m_dumpFile<<iter->first<<endl;
		m_dumpFile<<"\t";
		m_dumpFile<<iter->second->Dump();
		m_dumpFile<<endl;
	}
}

void RenderObjectManager::RemoveRenderObject(const Message& msg)
{
	string objName;
	QueueFormat qFormat;
	AuxUnGroupArgus(msg.p,objName,qFormat);
	if(m_renderQueueMap.find(qFormat)!=m_renderQueueMap.end())
		m_renderQueueMap[qFormat]->RemoveObject(objName);
	else
		EXCEPTION("Can not find render queue")
}

void RenderObjectManager::RemoveAllQueue(const Message& msg)
{
	for(RenderQueueMap::iterator iter=m_renderQueueMap.begin();iter!=m_renderQueueMap.end();iter++)
	{
		iter->second->RemoveAllObject();
	}
}